package com.jn.zhinongbao.adapter.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.bean.Product;

import java.io.File;
import java.util.List;

public class MerchantProductAdapter extends RecyclerView.Adapter<MerchantProductAdapter.ProductViewHolder> {

    private List<Product> products;
    private OnProductActionListener listener;

    public interface OnProductActionListener {
        void onEditProduct(Product product);
        void onDeleteProduct(Product product);
        void onViewProduct(Product product);
    }

    public MerchantProductAdapter(List<Product> products, OnProductActionListener listener) {
        this.products = products;
        this.listener = listener;
    }

    public void updateProducts(List<Product> newProducts) {
        this.products = newProducts;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_merchant_product, parent, false);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
        Product product = products.get(position);
        holder.bind(product);
    }

    @Override
    public int getItemCount() {
        return products.size();
    }

    public class ProductViewHolder extends RecyclerView.ViewHolder {
        private ImageView ivProduct;
        private TextView tvName;
        private TextView tvPrice;
        private TextView tvLikes;
        private TextView tvLocation;
        private ImageView ivMore;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);
            ivProduct = itemView.findViewById(R.id.iv_product);
            tvName = itemView.findViewById(R.id.tv_name);
            tvPrice = itemView.findViewById(R.id.tv_price);
            tvLikes = itemView.findViewById(R.id.tv_likes);
            tvLocation = itemView.findViewById(R.id.tv_location);
            ivMore = itemView.findViewById(R.id.iv_more);
        }

        public void bind(Product product) {
            tvName.setText(product.getName());
            tvPrice.setText(String.format("¥%.2f", product.getPrice()));
            tvLikes.setText(String.format("%d人想要", product.getLikes()));
            
            // 显示发货地址
            if (product.getLocation() != null && !product.getLocation().isEmpty()) {
                tvLocation.setText(product.getLocation());
                tvLocation.setVisibility(View.VISIBLE);
            } else {
                tvLocation.setVisibility(View.GONE);
            }
            
            // 加载图片
            loadProductImage(product.getImageUrl());
            
            // 设置点击事件
            itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onViewProduct(product);
                }
            });

            // 更多选项菜单
            ivMore.setOnClickListener(v -> showPopupMenu(v, product));
        }

        private void showPopupMenu(View view, Product product) {
            PopupMenu popup = new PopupMenu(view.getContext(), view);
            popup.getMenuInflater().inflate(R.menu.merchant_product_menu, popup.getMenu());
            
            popup.setOnMenuItemClickListener(item -> {
                int id = item.getItemId();
                if (id == R.id.action_edit) {
                    if (listener != null) listener.onEditProduct(product);
                    return true;
                } else if (id == R.id.action_delete) {
                    if (listener != null) listener.onDeleteProduct(product);
                    return true;
                }
                return false;
            });
            
            popup.show();
        }
        
        private void loadProductImage(String imageUrl) {
            if (imageUrl == null || imageUrl.isEmpty()) {
                ivProduct.setImageResource(R.drawable.ic_launcher_foreground);
                return;
            }
            
            Context context = itemView.getContext();
            
            // 判断是文件路径还是content URI
            Object imageSource;
            if (imageUrl.startsWith("/")) {
                // 文件路径
                File imageFile = new File(imageUrl);
                if (imageFile.exists()) {
                    imageSource = imageFile;
                } else {
                    // 文件不存在，显示默认图片
                    ivProduct.setImageResource(R.drawable.ic_launcher_foreground);
                    return;
                }
            } else if (imageUrl.startsWith("content://")) {
                // content URI
                imageSource = Uri.parse(imageUrl);
            } else {
                // 其他情况，直接使用字符串
                imageSource = imageUrl;
            }
            
            // 使用Glide加载图片
            Glide.with(context)
                    .load(imageSource)
                    .placeholder(R.drawable.ic_launcher_foreground)
                    .error(R.drawable.ic_launcher_foreground)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .centerCrop()
                    .override(300, 300)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            if (e != null) {
                                e.printStackTrace();
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(ivProduct);
        }
    }
} 